﻿using System;
using System.Collections;
using System.Data;

using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

using System.Text;
using TimKen.BussLogic;
using System.Threading;

namespace TimKen.Web.Admin.Ajax
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class TypeOption : IHttpHandler
    {
        ProductManager pm = new ProductManager();
        PCategoryManager ptm = new PCategoryManager();
        //标示产品还是类型所构造出来的form决定数据绑定的值
        int type = 0;
        #region IHttpHandle
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string categoryID = HttpContext.Current.Request.QueryString["CategoryID"];
            string productid = HttpContext.Current.Request.QueryString["ProductID"];
          
            DataSet ds = new DataSet();

        

            DataTable dt = null;
            if (!string.IsNullOrEmpty(productid))
            {
                ds = pm.GetAttributeWithValueByProductID(productid);
                dt = ConvertTable(ds.Tables[0]);
                type = 1;
            }
            else
            {
                ds = ptm.GetOptionByCategory(categoryID);
                dt = ConvertTable(ds.Tables[0]);
                type = 2;

            }
            context.Response.Write(ProcessOption(dt, type));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #endregion

        public DataTable ConvertTable(DataTable odt)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("OptionID");
            dt.Columns.Add("OptionValue");
            dt.Columns.Add("OptionValueEN");
            dt.Columns.Add("FieldMetaData");
            dt.Columns.Add("FieldType");
            dt.Columns.Add("OptionName");
            dt.Columns.Add("FieldMetaDataEN");
            dt.Columns.Add("LanguageID");

            //中文属性
          
           DataRow[] drs = odt.Select("LanguageID=1");

            foreach (DataRow dr in drs)
            {
                DataRow ndr = dt.NewRow();
                ndr["OptionID"] = dr["OptionID"];

                ndr["FieldMetaData"] = dr["FieldMetaData"];
                ndr["FieldType"] = dr["FieldType"];

                if(GetLanguageID() == "1")
                ndr["OptionName"] = dr["OptionName"];

                ndr["LanguageID"] = dr["LanguageID"];


                //英文属性
                DataRow[] sdrs = odt.Select("LanguageID=2 and OptionID=" + dr["OptionID"].ToString());
                if (sdrs != null && sdrs.Length > 0)
                {
                    ndr["FieldMetaDataEN"] = sdrs[0]["FieldMetaData"].ToString();
                    if (odt.Columns.Contains("OptionValue"))
                    {
                        ndr["OptionValueEN"] = sdrs[0]["OptionValue"].ToString();
                    }

                    if (GetLanguageID() == "2")
                        ndr["OptionName"] = sdrs[0]["OptionName"];
                }
                if (odt.Columns.Contains("OptionValue")) 
                {
                    ndr["OptionValue"] = dr["OptionValue"];
                }


                dt.Rows.Add(ndr);
            }
            return dt;
        }
        /// <summary>
        /// 获取语言
        /// </summary>
        /// <returns></returns>
        private string GetLanguageID()
        {
            switch (Thread.CurrentThread.CurrentUICulture.ToString())
            {
                case "zh-CN": return "1";
                case "en-US": return "2";
                default: return "1";
            }
        }
        private string ProcessOption(DataTable dt, int type)
        {
            StringBuilder sb = new StringBuilder();
            string txttemp = "<input type=\"text\" value=\"{0}\" name=\"{1}\" id=\"{1}\"/>";
            string mutitxttemp = "<textarea  name=\"{1}\" id=\"{1}\">{0}</textarea>";
            string selecttemp = "<select id=\"{0}\" name=\"{0}\" onchange=\"SChange('{0}')\">{1}</select>";
            string selectoption = "<option value=\"{0}\" {1}>{2}</option>";

            sb.Append("<table id='AttrTable' name='AttrTable' class='Attribute'> ");
            StringBuilder hiddenField = new StringBuilder();
            hiddenField.Append("<input type=\"hidden\" id=\"OptionIDs\" name=\"OptionIDs\" value=\"");

            foreach (DataRow dr in dt.Rows)
            {
                hiddenField.Append(dr["OptionID"].ToString() + ",");
                string fielddata = "", fielddataEN = "", SelectOption = "", SelectOptionEN = "";
                if (type == 1)
                {
                    fielddata = dr["OptionValue"].ToString();
                    fielddataEN = dr["OptionValueEN"].ToString().Trim();

                }
                else
                {
                    fielddata = dr["FieldMetaData"].ToString().Trim();
                    fielddataEN = dr["FieldMetaDataEN"].ToString().Trim();

                }

                SelectOption = dr["FieldMetaData"].ToString().Trim();
                SelectOptionEN = dr["FieldMetaDataEN"].ToString().Trim();

                switch (dr["FieldType"].ToString())
                {

                    case "0":
                        {
                            sb.Append("<tr><td>" + dr["OptionName"].ToString() + "</td>");
                            sb.Append("<td><img src=\"/Images/Chinese.gif\" alt=\"中文\" style=\"border-width:0px;\"/>");
                            sb.Append(string.Format(txttemp, fielddata, "att_" + dr["OptionID"].ToString() + "cn"));
                            sb.Append("</td><td><img src=\"/Images/English.gif\" alt=\"English\" style=\"border-width:0px;\"/>");
                            sb.Append(string.Format(txttemp, fielddataEN, "att_" + dr["OptionID"].ToString() + "en"));
                            sb.Append("</td></tr>");
                        }; break;
                    case "1":
                        {
                            sb.Append("<tr><td>" + dr["OptionName"].ToString() + "</td>");
                            sb.Append("<td><img src=\"/Images/Chinese.gif\" alt=\"中文\" style=\"border-width:0px;\"/>");
                            sb.Append(string.Format(mutitxttemp, fielddata, "att_" + dr["OptionID"].ToString() + "cn"));
                            sb.Append("</td><td><img src=\"/Images/English.gif\" alt=\"English\" style=\"border-width:0px;\"/>");
                            sb.Append(string.Format(mutitxttemp, fielddataEN, "att_" + dr["OptionID"].ToString() + "en"));
                            sb.Append("</td></tr>");
                        }; break;
                    case "2":
                        {
                            if (!string.IsNullOrEmpty(SelectOption) || !string.IsNullOrEmpty(SelectOptionEN))
                            {
                                sb.Append("<tr><td>" + dr["OptionName"].ToString() + "</td>");
                                if (!string.IsNullOrEmpty(SelectOption))
                                {

                                    StringBuilder innersb = new StringBuilder();
                                    string[] metadatas = SelectOption.Split(',');
                                    sb.Append("<td><img src=\"/Images/Chinese.gif\" alt=\"中文\" style=\"border-width:0px;\"/>");
                                    foreach (string s in metadatas)
                                    {
                                        string[] idval = s.Split(':');
                                        if (idval.Length == 2)
                                        {
                                            string selected = "";
                                            if (fielddata == idval[0])
                                            {
                                                selected = "selected";
                                            }
                                            else
                                            {
                                                selected = "";
                                            }
                                            innersb.Append(string.Format(selectoption, idval[0], selected, idval[1]));
                                        }
                                    }
                                    sb.Append(string.Format(selecttemp, "att_" + dr["OptionID"].ToString() + "cn", innersb.ToString()));
                                    sb.Append("</td>");
                                }
                                if (!string.IsNullOrEmpty(SelectOptionEN))
                                {
                                    StringBuilder innersbEN = new StringBuilder();
                                    string[] metadataENs = SelectOptionEN.Split(',');
                                    sb.Append("<td><img src=\"/Images/English.gif\" alt=\"English\" style=\"border-width:0px;\"/>");
                                    foreach (string s in metadataENs)
                                    {
                                        string[] idval = s.Split(':');
                                        if (idval.Length == 2)
                                        {
                                            string selected = "";
                                            if (fielddata == idval[0])
                                            {
                                                selected = "selected";
                                            }
                                            else
                                            {
                                                selected = "";
                                            }
                                            innersbEN.Append(string.Format(selectoption, idval[0], selected, idval[1]));
                                        }
                                    }
                                    sb.Append(string.Format(selecttemp, "att_" + dr["OptionID"].ToString() + "en", innersbEN.ToString()));
                                    sb.Append("</td>");
                                }
                                sb.Append("</tr>");
                            }

                        }; break;
                }
            }

            hiddenField.Length--;
            hiddenField.Append("\"/>");
            sb.Append("</table>");
            sb.Append(hiddenField.ToString());

            sb.Append("<script>");
            sb.Append("");
            sb.Append("</script>");
            return sb.ToString();

        }

    }
}
